package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.IMAGE_UPLOAD_DIR;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {

//        1. 校验手机号是否符合要求
        if (RegexUtils.isPhoneInvalid(phone)) {
//        2. 如果不符合返回错误信息
            return Result.fail("手机号错误，请重新输入！");
        }
//        3. 符合，生成验证码
        String code = RandomUtil.randomString(6);
//        4. 保存验证码到session
//        session.setAttribute("user", code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);


//        5.发送验证码
        log.debug(phone + "的验证码发送成功，验证码是：" + code);
//        返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

//        1.校验手机号与验证码
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
//        2.校验失败返回信息
        if (redisCode == null || !redisCode.equals(code)) {

            return Result.fail("手机号或验证码有误，请重新输入！");
        }
//        生成token
        String token = UUID.randomUUID().toString(true);


//        3.根据手机号查询用户是否注册
        User user = query().eq("phone", phone).one();

        if (null == user) {
//            4.没有注册，创建新用户
            user = createUserWithPhone(phone);
        }
//        System.out.println(user.toString());
//        5.已经存在，登陆,将信息保存到session中
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,
                new HashMap<>(), CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())
        );
        System.out.println(userMap);
        String tokenKey = LOGIN_USER_KEY + token;

//        userMap.forEach((key, value) -> {
//            if (null != value) userMap.put(key, String.valueOf(value));
//        });
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        System.out.println(user.toString());
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(8));
        save(user);
        return user;
    }
}
